package cn.harry.cabinet.view

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Point
import android.hardware.Camera
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.SurfaceView
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.arcface.engine.FaceEngineManager
import cn.harry.cabinet.arcface.faceserver.FaceServer
import cn.harry.cabinet.arcface.model.DrawInfo
import cn.harry.cabinet.arcface.model.FacePreviewInfo
import cn.harry.cabinet.arcface.util.ConfigUtil
import cn.harry.cabinet.arcface.util.DrawHelper
import cn.harry.cabinet.arcface.util.camera.CameraHelper
import cn.harry.cabinet.arcface.util.camera.CameraListener
import cn.harry.cabinet.arcface.util.face.FaceHelper
import cn.harry.cabinet.arcface.util.face.FaceListener
import cn.harry.cabinet.arcface.util.face.RecognizeColor
import cn.harry.cabinet.arcface.util.face.RequestFeatureStatus
import cn.harry.cabinet.arcface.widget.FaceRectView
import cn.harry.cabinet.model.entity.User
import cn.harry.cabinet.model.enums.UserStatus
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.repository.UserRepository
import cn.harry.cabinet.utils.AppConfigKeys
import cn.harry.cabinet.utils.VoiceHelper
import cn.harry.cabinet.utils.logFaceRecognition
import com.arcsoft.face.AgeInfo
import com.arcsoft.face.ErrorInfo
import com.arcsoft.face.FaceEngine
import com.arcsoft.face.FaceFeature
import com.arcsoft.face.GenderInfo
import com.arcsoft.face.LivenessInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap

/**
 * 人脸识别验证页面
 */
class FaceRecognitionActivity : BaseAuthActivity(), ViewTreeObserver.OnGlobalLayoutListener {

    companion object {
        private const val TAG = "FaceRecognitionActivity"
        private const val CAMERA_PERMISSION_REQUEST = 100
        private const val MAX_DETECT_NUM = 10
        private const val SIMILAR_THRESHOLD = 0.8f
        private const val FAIL_RETRY_INTERVAL = 1000L
        private const val MAX_RETRY_TIME = 3
    }

    // UI组件
    private lateinit var surfaceView: SurfaceView
    private lateinit var faceRectView: FaceRectView
    private lateinit var statusText: TextView
    private lateinit var subStatusText: TextView
    private lateinit var cameraHintText: TextView

    // 相机相关
    private var cameraHelper: CameraHelper? = null
    private var drawHelper: DrawHelper? = null
    private var previewSize: Camera.Size? = null

    // 使用后置摄像头进行人脸识别（彩色显示）
    // 注意：该设备的前置摄像头是黑白的，所以使用后置摄像头以获得彩色预览
    private val rgbCameraID = Camera.CameraInfo.CAMERA_FACING_BACK

    // 引擎相关
    private var ftEngine: FaceEngine? = null
    private var frEngine: FaceEngine? = null
    private var flEngine: FaceEngine? = null
    private var ftInitCode = -1
    private var frInitCode = -1
    private var flInitCode = -1

    // 人脸辅助类
    private var faceHelper: FaceHelper? = null

    // 状态映射
    private val requestFeatureStatusMap = ConcurrentHashMap<Int, Int>()
    private val extractErrorRetryMap = ConcurrentHashMap<Int, Int>()

    // 线程管理
    private val delayedJobs = mutableListOf<Job>()

    // Repository访问
    private lateinit var userRepository: UserRepository
    private lateinit var configRepository: ConfigurationRepository

    // 状态标志
    private var isProcessing = false
    private var engineActivated = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_face_recognition)

        // 初始化Repository
        userRepository = UserRepository(application)
        configRepository = ConfigurationRepository(application)

        // 初始化视图
        initViews()

        // 应用主题
        applyTheme()

        // 设置点击事件
        setupClickListeners()

        // 检查引擎激活状态
        checkEngineActivation()
    }

    private fun initViews() {
        surfaceView = findViewById(R.id.surface_view)
        faceRectView = findViewById(R.id.face_rect_view)
        statusText = findViewById(R.id.tv_status)
        subStatusText = findViewById(R.id.tv_sub_status)
        cameraHintText = findViewById(R.id.tv_camera_hint)

        // 更新标题
        val titleText = findViewById<TextView>(R.id.tv_title)
        titleText.text = getPageTitle("人脸识别")

        // 初始化UI状态
        statusText.text = "正在初始化..."
        cameraHintText.text = "请将面部对准摄像头"

        // 在布局完成后初始化
        surfaceView.viewTreeObserver.addOnGlobalLayoutListener(this)
    }

    private fun setupClickListeners() {
        findViewById<ImageView>(R.id.btn_back)?.setOnClickListener {
            finish()
        }
    }

    /**
     * 检查引擎激活状态
     */
    private fun checkEngineActivation() {
        lifecycleScope.launch {
            try {
                // 从配置中读取激活状态
                val activatedConfig = withContext(Dispatchers.IO) {
                    configRepository.getByTypeAndKey(
                        AppConfigKeys.TYPE_FACE_RECOGNITION,
                        AppConfigKeys.KEY_FACE_ACTIVATED
                    )
                }

                engineActivated = activatedConfig?.value == "true"

                if (!engineActivated) {
                    statusText.text = "人脸识别引擎未激活"
                    Toast.makeText(
                        this@FaceRecognitionActivity,
                        "人脸识别引擎未激活，请先在系统配置中激活", Toast.LENGTH_LONG
                    ).show()
                    Log.e(TAG, "人脸识别引擎未激活")

                    // 延迟返回
                    Handler(Looper.getMainLooper()).postDelayed({
                        finish()
                    }, 2000)
                    return@launch
                }
                // 检查相机权限
                checkCameraPermission()
                // 语音提示
                VoiceHelper.speak("请将脸部对准摄像头")


            } catch (e: Exception) {
                Log.e(TAG, "检查引擎激活状态失败", e)
                statusText.text = "初始化失败"
                Toast.makeText(this@FaceRecognitionActivity, "初始化失败", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    }

    /**
     * 检查相机权限
     */
    private fun checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.CAMERA),
                CAMERA_PERMISSION_REQUEST
            )
        } else {
            // 权限已授予，等待布局完成后初始化
            Log.i(TAG, "相机权限已授予")
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "相机权限已授予")
                // 权限授予后，等待布局完成
            } else {
                Toast.makeText(this, "需要相机权限才能使用人脸识别", Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }

    override fun onGlobalLayout() {
        surfaceView.viewTreeObserver.removeOnGlobalLayoutListener(this)
        Log.i(TAG, "布局完成，开始初始化引擎和相机")

        // 初始化人脸服务
        FaceServer.getInstance().init(this)
        Log.i(TAG, "FaceServer 初始化完成")

        // 初始化引擎
        initEngine()

        // 初始化相机
        initCamera()
    }

    /**
     * 初始化引擎
     */
    private fun initEngine() {
        if (!engineActivated) {
            Log.e(TAG, "人脸引擎未激活")
            statusText.text = "人脸引擎未激活"
            return
        }

        try {
            statusText.text = "正在初始化引擎..."

            // 使用全局引擎管理器获取引擎实例
            val engineManager = FaceEngineManager.getInstance()
            val (ft, fr, fl) = engineManager.getEngines(this, MAX_DETECT_NUM)

            if (ft == null || fr == null || fl == null) {
                Log.e(TAG, "从全局管理器获取引擎失败")
                statusText.text = "引擎初始化失败"
                Toast.makeText(this, "人脸识别引擎初始化失败", Toast.LENGTH_SHORT).show()
                return
            }

            ftEngine = ft
            frEngine = fr
            flEngine = fl

            ftInitCode = ErrorInfo.MOK
            frInitCode = ErrorInfo.MOK
            flInitCode = ErrorInfo.MOK

            Log.i(TAG, "引擎初始化成功")
            statusText.text = "引擎初始化成功"

        } catch (e: Exception) {
            Log.e(TAG, "初始化引擎异常", e)
            statusText.text = "引擎初始化异常"
            Toast.makeText(this, "引擎初始化异常: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 释放引擎引用
     */
    private fun unInitEngine() {
        try {
            val engineManager = FaceEngineManager.getInstance()
            engineManager.releaseEngines()

            Log.i(TAG, "已释放引擎引用")

            ftEngine = null
            frEngine = null
            flEngine = null
            ftInitCode = -1
            frInitCode = -1
            flInitCode = -1

        } catch (e: Exception) {
            Log.e(TAG, "释放引擎引用失败", e)
        }
    }

    /**
     * 初始化相机
     */
    private fun initCamera() {
        statusText.text = "正在初始化相机..."

        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)

        val faceListener = object : FaceListener {
            override fun onFail(e: Exception) {
                Log.e(TAG, "FaceListener onFail: ${e.message}")
            }

            override fun onFaceFeatureInfoGet(
                faceFeature: FaceFeature?,
                requestId: Int?,
                errorCode: Int?
            ) {
                if (faceFeature != null && requestId != null) {
                    Log.i(TAG, "特征提取成功")
                    searchFace(faceFeature, requestId)
                } else {
                    if (increaseAndGetValue(extractErrorRetryMap, requestId!!) > MAX_RETRY_TIME) {
                        extractErrorRetryMap[requestId] = 0
                        faceHelper?.setName(requestId, "识别失败")
                        requestFeatureStatusMap[requestId] = RequestFeatureStatus.FAILED
                        retryRecognizeDelayed(requestId)
                    } else {
                        requestFeatureStatusMap[requestId] = RequestFeatureStatus.TO_RETRY
                    }
                }
            }

            override fun onFaceLivenessInfoGet(
                livenessInfo: LivenessInfo?,
                requestId: Int?,
                errorCode: Int?
            ) {
                // 不进行活体检测
            }
        }

        val cameraListener = object : CameraListener {
            override fun onCameraOpened(
                camera: Camera,
                cameraId: Int,
                displayOrientation: Int,
                isMirror: Boolean
            ) {
                val lastPreviewSize = previewSize
                previewSize = camera.parameters.previewSize

                Log.i(TAG, "相机已打开 - 预览尺寸: ${previewSize!!.width}x${previewSize!!.height}")

                drawHelper = DrawHelper(
                    previewSize!!.width, previewSize!!.height,
                    surfaceView.width, surfaceView.height,
                    displayOrientation, cameraId, isMirror, false, false
                )

                if (faceHelper == null ||
                    lastPreviewSize == null ||
                    lastPreviewSize.width != previewSize!!.width ||
                    lastPreviewSize.height != previewSize!!.height
                ) {

                    var trackedFaceCount: Int? = null
                    if (faceHelper != null) {
                        trackedFaceCount = faceHelper?.trackedFaceCount
                        faceHelper?.release()
                    }

                    faceHelper = FaceHelper.Builder()
                        .ftEngine(ftEngine)
                        .frEngine(frEngine)
                        .flEngine(flEngine)
                        .frQueueSize(MAX_DETECT_NUM)
                        .flQueueSize(MAX_DETECT_NUM)
                        .previewSize(previewSize)
                        .faceListener(faceListener)
                        .trackedFaceCount(
                            trackedFaceCount ?: ConfigUtil.getTrackedFaceCount(
                                applicationContext
                            )
                        )
                        .build()
                }

                statusText.text = "请将面部对准摄像头"
                subStatusText.text = "系统将自动识别"
            }

            override fun onPreview(nv21: ByteArray, camera: Camera) {
                if (faceHelper == null) {
                    return
                }

                faceRectView.clearFaceInfo()

                try {
                    val facePreviewInfoList = faceHelper?.onPreviewFrame(nv21)
                    if (facePreviewInfoList != null && drawHelper != null) {
                        drawPreviewInfo(facePreviewInfoList)
                    }

                    clearLeftFace(facePreviewInfoList)

                    if (facePreviewInfoList != null && facePreviewInfoList.isNotEmpty() && previewSize != null) {
                        for (i in facePreviewInfoList.indices) {
                            val status = requestFeatureStatusMap[facePreviewInfoList[i].trackId]
                            if (status == null || status == RequestFeatureStatus.TO_RETRY) {
                                requestFeatureStatusMap[facePreviewInfoList[i].trackId] =
                                    RequestFeatureStatus.SEARCHING
                                faceHelper?.requestFaceFeature(
                                    nv21, facePreviewInfoList[i].faceInfo,
                                    previewSize!!.width, previewSize!!.height,
                                    FaceEngine.CP_PAF_NV21, facePreviewInfoList[i].trackId
                                )
                            }
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "预览帧处理异常", e)
                }
            }

            override fun onCameraClosed() {
                Log.i(TAG, "相机已关闭")
            }

            override fun onCameraError(e: Exception) {
                Log.e(TAG, "相机错误: ${e.message}")
                statusText.text = "相机错误"
                Toast.makeText(
                    this@FaceRecognitionActivity,
                    "相机错误: ${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }

            override fun onCameraConfigurationChanged(cameraID: Int, displayOrientation: Int) {
                drawHelper?.cameraDisplayOrientation = displayOrientation
                Log.i(TAG, "相机配置已更改")
            }
        }

        cameraHelper = CameraHelper.Builder()
            .previewViewSize(Point(surfaceView.measuredWidth, surfaceView.measuredHeight))
            .previewSize(Point(640, 480))
            .rotation(windowManager.defaultDisplay.rotation)
            .specificCameraId(rgbCameraID)
            .isMirror(false)
            .previewOn(surfaceView)
            .cameraListener(cameraListener)
            .build()

        cameraHelper?.init()
        cameraHelper?.start()
    }

    /**
     * 绘制人脸框
     */
    private fun drawPreviewInfo(facePreviewInfoList: List<FacePreviewInfo>) {
        val drawInfoList = ArrayList<DrawInfo>()
        for (i in facePreviewInfoList.indices) {
            val name = faceHelper?.getName(facePreviewInfoList[i].trackId)
            val recognizeStatus = requestFeatureStatusMap[facePreviewInfoList[i].trackId]

            var color = RecognizeColor.COLOR_SUCCESS
            if (recognizeStatus != null) {
                color = when (recognizeStatus) {
                    RequestFeatureStatus.FAILED -> RecognizeColor.COLOR_FAILED
                    RequestFeatureStatus.SUCCEED -> RecognizeColor.COLOR_SUCCESS
                    else -> RecognizeColor.COLOR_SUCCESS
                }
            }

            drawInfoList.add(
                DrawInfo(
                    drawHelper?.adjustRect(facePreviewInfoList[i].faceInfo.rect),
                    GenderInfo.UNKNOWN, AgeInfo.UNKNOWN_AGE, LivenessInfo.UNKNOWN, color,
                    name ?: facePreviewInfoList[i].trackId.toString()
                )
            )
        }
        drawHelper?.draw(faceRectView, drawInfoList)
    }

    /**
     * 清除已离开的人脸
     */
    private fun clearLeftFace(facePreviewInfoList: List<FacePreviewInfo>?) {
        if (facePreviewInfoList == null || facePreviewInfoList.isEmpty()) {
            requestFeatureStatusMap.clear()
            extractErrorRetryMap.clear()
            cancelDelayedJobs()
            return
        }

        val keys = requestFeatureStatusMap.keys()
        while (keys.hasMoreElements()) {
            val key = keys.nextElement()
            var contained = false
            for (facePreviewInfo in facePreviewInfoList) {
                if (facePreviewInfo.trackId == key) {
                    contained = true
                    break
                }
            }
            if (!contained) {
                requestFeatureStatusMap.remove(key)
                extractErrorRetryMap.remove(key)
            }
        }
    }

    /**
     * 搜索人脸
     */
    private fun searchFace(frFace: FaceFeature, requestId: Int) {
        lifecycleScope.launch {
            try {
                Log.d(TAG, "开始搜索人脸，requestId: $requestId")

                val compareResult = withContext(Dispatchers.Default) {
                    FaceServer.getInstance().getTopOfFaceLib(frFace)
                }

                Log.d(
                    TAG,
                    "比对结果: userName=${compareResult?.featureCode}, similar=${compareResult?.similar}"
                )

                if (isProcessing) {
                    Log.d(TAG, "正在处理中，跳过")
                    return@launch
                }

                if (compareResult == null || compareResult.featureCode == null) {
                    requestFeatureStatusMap[requestId] = RequestFeatureStatus.FAILED
                    faceHelper?.setName(requestId, "未识别 $requestId")
                    Log.w(TAG, "未找到匹配的人脸")
                    return@launch
                }

                if (compareResult.similar > SIMILAR_THRESHOLD) {
                    requestFeatureStatusMap[requestId] = RequestFeatureStatus.SUCCEED
                    faceHelper?.setName(requestId, compareResult.featureCode)

                    // 记录识别成功日志
                    logFaceRecognition(
                        scope = lifecycleScope,
                        result = "SUCCESS",
                        description = "人脸识别成功：${compareResult.featureCode}",
                        detailData = mapOf(
                            "featureCode" to compareResult.featureCode,
                            "similarity" to compareResult.similar,
                            "threshold" to SIMILAR_THRESHOLD
                        )
                    )

                    // 识别成功，验证用户
                    verifyFace(compareResult.featureCode)
                } else {
                    faceHelper?.setName(requestId, "未注册")
                    retryRecognizeDelayed(requestId)
                }
            } catch (e: Exception) {
                if (!isProcessing) {
                    Log.e(TAG, "搜索人脸出错", e)
                    faceHelper?.setName(requestId, "搜索出错")
                    retryRecognizeDelayed(requestId)
                }
            }
        }
    }

    /**
     * 验证人脸
     */
    private fun verifyFace(featureCode: String) {
        if (isProcessing) {
            return
        }
        isProcessing = true

        try {
            Log.d(TAG, "开始验证人脸身份: $featureCode")

            lifecycleScope.launch {
                try {
                    // 根据特征码获取用户
                    val user = withContext(Dispatchers.IO) {
                        userRepository.getAllUsers().find { it.featureCode == featureCode }
                    }

                    if (user == null) {
                        VoiceHelper.speak("未绑定用户")
                        statusText.text = "人脸识别验证失败: 未绑定用户"
                        Toast.makeText(
                            this@FaceRecognitionActivity,
                            "未找到对应用户",
                            Toast.LENGTH_SHORT
                        ).show()

                        // 记录验证失败日志
                        logFaceRecognition(
                            scope = lifecycleScope,
                            result = "FAILED",
                            description = "人脸验证失败：特征码未绑定用户",
                            errorMessage = "特征码 $featureCode 未找到对应用户",
                            detailData = mapOf("featureCode" to featureCode)
                        )

                        isProcessing = false
                        return@launch
                    }

                    // 检查用户状态
                    if (user.status == UserStatus.DISABLED) {
                        VoiceHelper.speak("用户已被禁用")
                        statusText.text = "用户已被禁用"
                        Toast.makeText(
                            this@FaceRecognitionActivity,
                            "用户已被禁用",
                            Toast.LENGTH_SHORT
                        ).show()

                        // 记录验证失败日志
                        logFaceRecognition(
                            scope = lifecycleScope,
                            result = "FAILED",
                            userId = user.id,
                            employeeId = user.employeeId,
                            userName = user.name,
                            description = "人脸验证失败：用户已被禁用",
                            errorMessage = "用户 ${user.name}(${user.employeeId}) 状态为禁用"
                        )

                        isProcessing = false
                        return@launch
                    }

                    // 验证成功
                    statusText.text = "验证成功"
                    cameraHintText.text = "识别成功: ${user.name}"

                    // 记录验证成功日志
                    logFaceRecognition(
                        scope = lifecycleScope,
                        result = "SUCCESS",
                        userId = user.id,
                        employeeId = user.employeeId,
                        userName = user.name,
                        description = "人脸验证成功：${user.name}(${user.employeeId})",
                        detailData = mapOf(
                            "featureCode" to featureCode,
                            "actionType" to (actionType ?: "UNKNOWN")
                        )
                    )

                    Log.d(TAG, "验证成功，准备跳转")
                    onAuthSuccess(user)

                } catch (e: Exception) {
                    Log.e(TAG, "验证人脸过程中发生错误", e)
                    statusText.text = "验证失败: ${e.message}"
                    Toast.makeText(this@FaceRecognitionActivity, "验证失败", Toast.LENGTH_SHORT)
                        .show()
                    isProcessing = false
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "验证人脸异常", e)
            isProcessing = false
        }
    }

    private fun onAuthSuccess(user: User) {
        // 取仪器场景：人脸识别成功后跳转到刷卡页面
        if (actionType == ACTION_TAKE) {
            val intent = Intent(this, CardScanActivity::class.java)
            intent.putExtra(EXTRA_ACTION_TYPE, ACTION_TAKE)
            intent.putExtra("user_id", user.id)
            intent.putExtra("user_name", user.name)
            intent.putExtra("employee_id", user.employeeId)
            intent.putExtra("auth_method", "face")
            intent.putExtra("feature_code", user.featureCode) // 记录人脸识别特征码
            startActivity(intent)
            finish()
        } else {
            // 还仪器场景：使用默认逻辑
            super.onAuthSuccess(user, "face")
        }
    }

    /**
     * 延迟重新进行人脸识别
     */
    private fun retryRecognizeDelayed(requestId: Int) {
        requestFeatureStatusMap[requestId] = RequestFeatureStatus.FAILED
        val job = lifecycleScope.launch {
            delay(FAIL_RETRY_INTERVAL)
            faceHelper?.setName(requestId, requestId.toString())
            requestFeatureStatusMap[requestId] = RequestFeatureStatus.TO_RETRY
        }
        delayedJobs.add(job)
    }

    /**
     * 取消所有延迟任务
     */
    private fun cancelDelayedJobs() {
        delayedJobs.forEach { it.cancel() }
        delayedJobs.clear()
    }

    /**
     * 增加并获取值
     */
    private fun increaseAndGetValue(countMap: ConcurrentHashMap<Int, Int>, key: Int): Int {
        var value = countMap[key]
        if (value == null) {
            value = 0
        }
        countMap[key] = ++value
        return value
    }

    override fun onDestroy() {
        super.onDestroy()

        Log.d(TAG, "onDestroy: 开始清理资源")

        try {
            // 停止所有异步任务
            cancelDelayedJobs()

            // 释放相机资源
            if (cameraHelper != null) {
                cameraHelper?.stop()
                cameraHelper?.release()
                cameraHelper = null
                Log.d(TAG, "相机资源已释放")
            }

            // 释放人脸辅助类
            if (faceHelper != null) {
                faceHelper?.release()
                faceHelper = null
                Log.d(TAG, "人脸辅助类已释放")
            }

            // 释放引擎引用
            unInitEngine()

            // 销毁人脸服务
            FaceServer.getInstance().unInit()
            Log.d(TAG, "人脸服务已销毁")

            // 保存跟踪的人脸数量
            if (faceHelper != null) {
                try {
                    ConfigUtil.setTrackedFaceCount(this, faceHelper?.trackedFaceCount ?: 0)
                } catch (e: Exception) {
                    Log.e(TAG, "保存跟踪人脸数量时出错", e)
                }
            }

            Log.d(TAG, "FaceRecognitionActivity资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "清理资源时出错", e)
        }
    }
}
